# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import MFRC522
import signal
import json
import requests

urlBorrow = "http://192.168.195.1:7550/api/newBorrow"
urlBook = "http://192.168.195.1:7550/api/newBook"
urlUser = "http://192.168.195.1:7550/api/newUser"
urlDoor = "http://192.168.195.1:7550/api/newLogin"
headers = {
  'Content-Type': 'application/json'
}


continue_reading = True

def end_read(signal,frame):
    global continue_reading
    print "Ctrl+C captured, ending read."
    continue_reading = False
    GPIO.cleanup()

signal.signal(signal.SIGINT, end_read)

MIFAREReader = MFRC522.MFRC522()

# Welcome message
print "Welcome to the MFRC522 data read example"
print "Press Ctrl-C to stop."
card_UID = ""

def RfUID():
    # 寻卡    
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
    # 获取卡片ID
    (status,uid) = MIFAREReader.MFRC522_Anticoll()
    # 判断UID是否读取成
    if status == MIFAREReader.MI_OK:
        # 输出UID
        card_UID = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])
        return card_UID

def RfRead():
    data = []
    # 寻卡    
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

    # 寻卡成功
    # if status == MIFAREReader.MI_OK:
    #     # print "寻卡成功！"
    
    # 获取卡片ID
    (status,uid) = MIFAREReader.MFRC522_Anticoll()

    # 判断UID是否读取成
    if status == MIFAREReader.MI_OK:
        # 输出UID
        card_UID = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])
        # print "卡号: %s" % (uid[0]+uid[1]+uid[2]+uid[3])
    
        # 默认密钥
        key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
        
        # 读取卡片
        MIFAREReader.MFRC522_SelectTag(uid)

        # 密钥验证
        status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

        # 验证成功
        if status == MIFAREReader.MI_OK:
            MIFAREReader.MFRC522_Write(8, default_book)
            rfdata =  MIFAREReader.MFRC522_Read(8)
            MIFAREReader.MFRC522_StopCrypto1()
            data.append(rfdata)
            data.append(card_UID)
            return data
        else:
            print "Authentication error"


bdata = []

default_person = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
default_book = [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]


while continue_reading:
    res = RfRead()
    if res:
        if res[0][1] == 0:
            # 添加书
            # if res[0][15] == 0:
            #     print "添加书"
            #     payload = json.dumps({"bid": res[1]})
            #     try:
            #         response = requests.request("POST", urlBook, headers=headers, data=payload,timeout=2)
            #     except:
            #         pass
            # # if back_data['code'][0] == '9001':
            #     (status,res[1]) = MIFAREReader.MFRC522_Anticoll()
            #     if status == MIFAREReader.MI_OK:
            #         MIFAREReader.MFRC522_Write(8, default_book)
            #         break
            #     print "添加成功！"
            #     break
            # 添加人
            if res[0][15] == 1:
                print "添加人"
                payload = json.dumps({"uid": res[1]})
                response = requests.request("POST", urlUser, headers=headers, data=payload,timeout=1)
                back_data = response.json()
            # if back_data['code'][0] == '9002':
                (status,res[1]) = MIFAREReader.MFRC522_Anticoll()
                if status == MIFAREReader.MI_OK:
                    MIFAREReader.MFRC522_Write(8, default_person)
                print "添加成功！"
                break
        # elif res[0][0]== 2:
        #     print "请选择借书人!"
        #     while True:
        #         bdata = RfRead()
        #         p_uid = RfUID()
        #         if bdata:
        #             if bdata[1] == 2:
        #                 payload = json.dumps({"uid": p_uid ,"bid":card_UID})
        #                 response = requests.request("POST", urlBorrow, headers=headers, data=payload,timeout=1)
        #                 print(response.text)
        #                 print("借书成功！")
        #                 continue_reading = False
        #                 break;
                 
        # elif card_data[1] == 1:
        #     payload = json.dumps({"uid": p_uid})
        #     response = requests.request("POST", urlDoor, headers=headers, data=payload,timeout=1)
        #     back_data = response.json()
        #     if back_data["code"][0] == "0000":
        #         print "开门成功！"
        #     continue_reading = False
            

